import uuid
# from flaskapp.model.db import db, Task
# from sqlalchemy.exc import SQLAlchemyError
from flaskapp.model.mongo import db
from datetime import datetime
from typing import Tuple

import logging
from bson import ObjectId
logger = logging.getLogger(__name__)



def task_get(pageIndex: int = 1, pageSize: int = 10, targetType: str = None) -> dict:
    try:
        logger.info(f"Fetching tasks for pageIndex: {pageIndex}, pageSize: {pageSize}, targetType: {targetType}")
        # query = Task.query.order_by(Task.timestamp.desc())
        # if targetType and targetType.upper() == "ALL":
        #     # 如果 class_name 是 "all" 或者 "ALL"，则不添加过滤条件，返回所有记录
        #     pass
        # elif targetType:
        #     # 否则，根据指定的 class_name 进行过滤
        #     query = query.filter(Task.targetType == targetType)
        # pagination = query.paginate(page=pageIndex, per_page=pageSize, error_out=False)
        # tasks = [task.to_dict() for task in pagination.items]
        condition={}
        if targetType and targetType.upper() == "ALL":
            pass
        elif targetType:
            condition["targetType"]=targetType
        total=db.task.count_documents(condition)
        items=[]
        page=db.task.find(condition).sort("timestamp").limit(pageSize).skip(pageSize*(pageIndex-1))
        for r in page:
            items.append(r)
            
        logger.info(f"Retrieved {len(items)} tasks from page {pageIndex}, total items: {total}")
        return {
            "tasks": items,
            "total": total
        }
    except BaseException as e:
        logger.error(f"Error retrieving tasks: {e}")
        return {"tasks": [], "total": 0}




def task_insert(taskServer: str, targetType: str, modelFrame: str, media: str, mediaID: str, conf: float, pid: str=None, fps: str=None) -> bool:
    try:
        current_datetime = datetime.now()

        # task = Task(id=str(uuid.uuid4()), targetType=targetType, modelFrame=modelFrame, media=media, mediaID=mediaID, confidence=conf, pid=pid, fps=fps, timestamp=current_datetime)
        # db.session.add(task)
        # db.session.commit()
        
        # task = { "targetType":targetType, "modelFrame":modelFrame, "media":media, "mediaID":mediaID, "confidence":conf, "pid":pid, "fps":fps, "timestamp":current_datetime}
        task = {"taskServer":taskServer, "targetType":targetType, "modelFrame":modelFrame, "media":media, "mediaID":mediaID, "confidence":conf, "pid":pid, "fps":fps, "timestamp":current_datetime}
        ret=db.task.insert_one(task)
        logger.info(f"Inserted task with id: {ret.inserted_id}")

        return True
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error inserting task: {e}")
        return False



def task_delete(task_id: str) -> bool:
    try:
        # task = Task.query.get(task_id)
        task=db.task.find_one({"_id":ObjectId(task_id)})
        if task:
            # db.session.delete(task)
            # db.session.commit()
            ret=db.task.delete_one({"_id":ObjectId(task_id)})
            logger.info(f"Deleted task with id: {ret.deleted_count}")
            return True
        logger.warning(f"Task with id: {task_id} not found")
        return False
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error deleting task: {e}")
        return False
    

def task_edit(id: str, taskServer: str, targetType: str, modelFrame: str, media: str, conf: float, fps: str) -> bool:
    try:
        task=db.task.find_one({"_id":ObjectId(id)})
        if task:
            task.taskServer = taskServer
            task.targetType = targetType
            task.modelFrame = modelFrame
            task.media = media
            task.confidence = conf
            task.fps = fps
            task.timestamp = datetime.now()  # 更新修改时间
            # db.session.commit()
            db.task.update_one({"_id":ObjectId(id)},task)
            logger.info(f"Updated task with id: {task.id}")
            return True
        logger.warning(f"Task with id: {id} not found")
        return False
    except BaseException as e:
        # db.session.rollback()
        logger.error(f"Error updating task: {e}")
        return False


def task_getStartInfo(id: str) -> dict:
    try:
        task=db.task.find_one({"_id":ObjectId(id)})
        if not task:
            logger.warning(f"Task with id: {id} not found")
            return None
        startInfo = {
            "detect_frame": task.modelFrame,
            "modelName": task.targetType,
            "url": task.media,
            "conf": task.confidence,
            "fps": task.fps,
            "mediaID": task.mediaID
        }
        return startInfo

    except Exception as e:
        logger.error(f"Unexpected error getting startInfo: {e}")
        return None


def task_getPIDByID(id: str) -> str:
    try:
        task=db.task.find_one({"_id":ObjectId(id)})
        if not task:
            logger.warning(f"Task with id: {id} not found")
            return None
        pid = task.pid
        return pid
    
    except Exception as e:
        logger.error(f"Unexpected error getting pid: {e}")
        return None

def task_getTaskServerByID(id: str) -> str:
    try:
        task = Task.query.get(id)
        if not task:
            logger.warning(f"Task with id: {id} not found")
            return None
        taskServer = task.taskServer
        return taskServer
    
    except Exception as e:
        logger.error(f"Unexpected error getting pid: {e}")
        return None

def task_update_pid(id: str, pid: str):
    try:
        task=db.task.find_one({"_id":ObjectId(id)})
        if not task:
            logger.warning(f"Task with id: {id} not found")
            return None
        task.pid = pid
        db.session.commit()
        return True
    
    except Exception as e:
        logger.error(f"Unexpected error getting pid: {e}")
        return False
